package com.leejoy.fangjiastore;

import android.os.Bundle;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.RadioGroup;


public class  MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener  {

    private Fragment[] fragments;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        Log.d("Device","Build,MODEL = "+ Build.MODEL);
        //TODO 检查横竖屏切换到时候, 这个数组对象和内部元素是否置空
        fragments = new Fragment[5];
        FragmentManager manager = getSupportFragmentManager();
        if(savedInstanceState !=null){
            //代表Activity重新创建, 内部的Fragment会自动添加
            int len = fragments.length;

            for (int i = 0; i < len; i++) {
                fragments[i] = manager.findFragmentByTag("f"+i);
            }
        }else {
            fragments[0] = new HomePageFragment();
            fragments[1] = new CategoryFragment();
            fragments[2] = new MineFragment();
            fragments[3] = new ShoppingCartFragment();
            fragments[4] = new MoreFragment();

            FragmentTransaction tx = manager.beginTransaction();

            int length = fragments.length;

            for (int i = 0; i < length; i++) {
                //添加Fragment, 并且指定tag, 利用tag在Activity重新创建的时候恢复查找出来
                tx.add(R.id.main_fragment_container, fragments[i], "f"+i);
                tx.hide(fragments[i]);
            }
            tx.show(fragments[0]);
            tx.commit();

        }
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_tab_bar);

        radioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //show, hide

        int index = 0;
        switch (checkedId){
            case R.id.main_tab_item_home_page:
                index = 0;
                break;
            case R.id.main_tab_item_category:
                index = 1;
                break;
            case R.id.main_tab_item_shopping_cart:
                index = 2;
                break;
            case R.id.main_tab_item_mine:
                index = 3;
            case R.id.main_tab_item_more:
                index = 4;
                break;
        }
        int length = fragments.length;

        FragmentManager manager=getSupportFragmentManager();

        FragmentTransaction tx=manager.beginTransaction();

        for (int i = 0; i < length; i++) {
            if(i==index){
                tx.show(fragments[i]);
            }else{
                tx.hide(fragments[i]);
            }
        }

        tx.commit();
    }
}
